﻿/* Author: yangzeming
* Date: 2013-12-10
* Desc: 拖动组件，为dialog等服务
*/
define(function (require, exports, module) {
     /**
     * 通过鼠标拖拽容器
     * @class
     * @param options 配置项
     * @param {String|HTMLElement|jQuery} options.handle 待拖拽的容器
     * @param {String|HTMLElement|jQuery} [options.target] 响应鼠标的容器
     * @param {String} [options.type] 限制可被拖动的方向'X'(X轴拖动), 'Y'(Y轴拖动), ''(自由拖动)
     * @param {Function} [options.onDown] 鼠标按下的回调
     * @param {Function} [options.onMove] 鼠标按下并移动时的回调
     * @param {Function} [options.onUp] 鼠标弹起的回调
     *
     * @example
     * new $.draggable({
     *     "handle" : ".dialog",
     *     "target" : ".dialog .title",
     *     "type" : '',  //自由拖动
     *     "onDown" : function(evt){
     *
     *     },
     *     "onMove" : function( evt, x, y){
     *         alert('x轴的偏移量: ' + x + ';y轴偏移量: ' + y);
     *     },
     *     "onUp" : function( evt ){
     *
     *     }
     * });
     */
    var Draggable = _.Class({
        initial: function (options) {
            this._eventStack = {};
            if(!options.handle)
			    return;
		    var s = $.extend({}, options);
		    var handle = $(s.handle);
		    var target = s.target && $(s.target);
		    var currPos = null;
		    var type = (s.type || '').toString().toUpperCase();
 		    handle[0].onselectstart = function() { return false; }
            handle.attr( "unselectable", "on" ).css( "MozUserSelect", "none" );

		    var _onDrag = null, _dragging = null;
		    var _mouseMove = function(evt){
			
			    var x = evt.pageX - _dragging[0],
				    y = evt.pageY - _dragging[1];
				
			    if(target){
				    var css = {};
				    if(type !== 'Y')
					    css.left = currPos.left + x;
				    if(type !== 'X')
					    css.top = currPos.top + y;
				    if(!$.isEmptyObject(css))
					    target.css(css);
			    }
				
			    if($.isFunction(s.onMove))
				    s.onMove(evt, x, y);
		    };
		    var _mouseUp = function(evt){
			    $(document).unbind("mousemove", _mouseMove).unbind("mouseup", _mouseUp);
			    _onDrag = false;
			    if($.isFunction(s.onUp))
				    s.onUp(evt);
		    };
		    var _mouseDown =  function(evt){
			    if(_onDrag) 
				    _mouseUp();
			    if($.isFunction(s.onDown))
				    s.onDown(evt);
			    if(target)
				    currPos = {left: target[0].offsetLeft, top: target[0].offsetTop};
			    _dragging = [evt.pageX, evt.pageY];
			    $(document).bind("mousemove", _mouseMove).bind("mouseup", _mouseUp);
		    };
		
		    s.handle.bind('mousedown', _mouseDown);
		
		    this.remove = function(){
			    $(document).unbind("mousemove", _mouseMove);
			    $(document).unbind("mousemove", _mouseUp);			
			    $(document).unbind("mousedown", _mouseDown);
		    };

		    this.destroy = function () {
			    handle.unbind('mousedown', _mouseDown);
		    }
        
        }


    });
module.exports = Draggable;
});